package org.lionsoul.websnail.store;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * Spider Visited manager based no HashMap
 * (Thread safe)
 *
 * @author chenxin<chenxin619315 @ gmail.com>
 */
public class HashMapVisited implements Visited
{
    private final static Integer MAP_VAL = new Integer(1);

    private Map<String, Integer> map;

    public HashMapVisited()
    {
        map = new ConcurrentHashMap<>(2000, 0.8f);
    }

    /**
     * create a visited with a default opacity and HashMap factor
     *
     * @param opacity
     * @param factor
     */
    public HashMapVisited(int opacity, float factor)
    {
        map = new ConcurrentHashMap<>(opacity, factor);
    }

    /**
     * @see Visited#add(String)
     */
    @Override
    public boolean add(String url)
    {
        map.put(url, MAP_VAL);
        return true;
    }

    /**
     * @see Visited#add(String[])
     */
    @Override
    public boolean add(String[] urls)
    {
        for (String url : urls) {
            if (!add(url)) return false;
        }

        return true;
    }

    /**
     * @see Visited#remove(String)
     */
    @Override
    public boolean remove(String url)
    {
        return (map.remove(url) == MAP_VAL);
    }

    /**
     * @see Visited#clear()
     */
    @Override
    public void clear()
    {
        map.clear();
    }

    /**
     * @see Visited#contains(String)
     */
    @Override
    public boolean contains(String url)
    {
        return map.containsKey(url);
    }

    /**
     * @see Visited#size()
     */
    public int size()
    {
        return map.size();
    }

    @Override
    public void close()
    {
        map.clear();
        map = null;
    }

}
